import { Notification } from 'element-ui'
import Router from '../../router/index'
export default {
  namespaced: true,
  state: {
    socketTask: null,   //ws链接
    webSocketPingTimer: null,  //心跳定时器
    webSocketPingTime: 10000,  // 心跳时间， 当前为10秒
    wedSocketReconnectCount: 0,  // 重连次数
    webSocketIsReconnect: true,  // 是否重连
    webSocketIsOpen: true,
    uid: null,  // ws登录的userId
    sid: null,   // ws 登录的token
    msg: []  // 接受到的消息
  },
  getters: {
    // 获取接收的信息
    socketMsgs: state => {
      return state.msg
    }
  },
  mutations: {
    //发送http请求登录后设置用户id 用于ws登录
    setUid(state, uid) {
      state.uid = uid
    },
    //发送http请求登录后设置用户token 用于ws登录
    setSid(state, sid) {
      state.sid = sid
    },

    setRecive(state, msg) {
      state.msg.push(msg)
    },

    emptyRecive(state) {
      state.msg.length = 0
    },
    //初始化ws 用户登录后调用
    webSocketInit(state) {
      let that = this
      // 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
      // state.socketTask = uni.connectSocket({
      //   url: "ws://127.0.0.1:8080/wds-demo-web-api/websocket",
      //   success(data) {
      //     console.log("websocket连接成功");
      //   },
      // });
      if ("WebSocket" in window) {
        console.log("您的浏览器支持 WebSocket!")
      }
      state.socketTask = new WebSocket(`ws://127.0.0.1:8080/wds-demo-web-api/websocket?uid=${state.uid}`)
      // ws连接开启后登录验证
      /*state.socketTask.onopen((res) => {
        console.log("WebSocket连接正常打开中...！");
        that.commit('websocket/webSocketLogin')
        //开始心跳
        that.commit('websocket/webSocketPing')
        // 注：只有连接正常打开中 ，才能正常收到消息
        state.socketTask.message((res) => {
          console.log("收到服务器内容：" + res.data);
          state.msg = JSON.parse(res.data)
        });
      });*/
      // 链接开启后登录验证
      /*state.socketTask.error((errMsg) => {
        console.log(errMsg)
        console.log("ws连接异常")
        that.commit('websocket/webSocketClose')
      });*/
      // 链接开启后登录验证
      /*state.socketTask.close((errMsg) => {
        console.log(errMsg)
        console.log("ws连接关闭")
        that.commit('websocket/webSocketClose')
      });*/
      //打开事件
      state.socketTask.onopen = function () {
        console.log("WebSocket连接正常打开中...！");
        //socket.send("这是来自客户端的消息" + location.href + new Date());
        // that.commit('websocket/webSocketLogin')
        //获得消息事件
        state.socketTask.onmessage = function (res) {
          console.log("收到服务器内容：" + res.data);
          Notification({
          dangerouslyUseHTMLString: true,
          message: '<strong> <i>你有新的消息！</i></strong>',
            onClick: function () {
                Router.push("notice-imsgloguser")
            }
          });
          /* <router-link to="/tabs">
                            <i class="el-icon-bell"></i>
                        </router-link>*/
          that.commit('websocket/setRecive', JSON.parse(res.data))
        };
      };

      //关闭事件
      state.socketTask.onclose = function (errMsg) {
        console.log(errMsg)
        console.log("ws连接关闭")
        that.commit('websocket/webSocketClose')
      };
      //发生了错误事件
      state.socketTask.onerror = function (errMsg) {
        console.log(errMsg)
        console.log("ws连接异常")
        that.commit('websocket/webSocketClose')
      }
    },

    webSocketLogin(state) {
      let that = this
      console.log("ws登录");
      const payload = {
        uid: state.uid,
        type: 1
      };
      that.commit('websocket/webSocketSend', payload);
      that.state.webSocketIsOpen = true
    },

    // 断开连接时
    webSocketClose(state) {
      let that = this
      // 修改状态为未连接
      state.webSocketIsOpen = false;
      state.webSocket = null;
      // 判断是否重连
      if (
        state.webSocketIsReconnect &&
        state.webSocketReconnectCount === 0
      ) {
        // 第一次直接尝试重连
        that.commit('websocket/webSocketReconnect');
      }
    },

    // 定时心跳
    webSocketPing() {
      let that = this
      that.state.webSocketPingTimer = setTimeout(() => {
        if (!that.state.webSocketIsOpen) {
          return false;
        }
        console.log("心跳");
        const payload = {
          type: 0
        };
        that.commit('websocket/webSocketSend', payload);
        clearTimeout(that.state.webSocketPingTimer);
        // 重新执行
        that.commit('websocket/webSocketPing');
      }, that.state.webSocketPingTime);
    },

    // WebSocket 重连
    webSocketReconnect(state) {
      let that = this
      if (state.webSocketIsOpen) {
        return false;
      }
      console.log("第" + state.webSocketReconnectCount + "次重连")
      state.webSocketReconnectCount += 1;
      // 判断是否到了最大重连次数
      if (state.webSocketReconnectCount >= 10) {
        this.webSocketWarningText = "重连次数超限";
        return false;
      }
      // 初始化
      console.log("开始重连")
      that.commit('websocket/webSocketInit');

      // 每过 5 秒尝试一次，检查是否连接成功，直到超过最大重连次数
      let timer = setTimeout(() => {
        that.commit('websocket/webSocketReconnect');
        clearTimeout(timer);
      }, 5000);
    },

    // 发送ws消息
    webSocketSend(state, payload) {
      let that = this
      state.socketTask.send(JSON.stringify(payload))
      that.state.sendMsgStatus = true
    }
  },
  actions: {
    webSocketInit({
                    commit
                  }, url) {
      commit('webSocketInit', url)
    },
    webSocketSend({
                    commit
                  }, p) {
      commit('webSocketSend', p)
    }
  }

}
